package com.gcsoftware.web.service;

import com.gcsoftware.configs.MailConfigs;
import com.gcsoftware.utils.*;
import com.gcsoftware.web.beans.T_GW_VERIFY;
import com.gcsoftware.web.mapper.T_COM_SYS_USERMAPPER;
import com.gcsoftware.web.mapper.T_GW_ROLEMAPPER;
import com.gcsoftware.authentications.beans.RoleInfo;
import com.gcsoftware.authentications.beans.UserInfo;
import com.gcsoftware.authentications.helper.ShiroUtils;
import com.gcsoftware.web.beans.T_COM_SYS_USER;
import com.gcsoftware.web.beans.T_COM_SYS_USERPWD;
import com.gcsoftware.utils.mail.MailUtils;
import com.gcsoftware.web.mapper.T_GW_VERIFYMAPPER;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.sql.SQLException;
import java.util.List;

/**
 * Created by qs on 2018/3/14.
 */
@Service("userService")
public class T_COM_SYS_USER_SERVICE {
    private org.slf4j.Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private T_COM_SYS_USERMAPPER mapper;

    @Autowired
    private T_GW_ROLEMAPPER roleMapper;

    @Autowired
    T_GW_VERIFYMAPPER verifyMapper;

    @Autowired
    MailConfigs mailConfigs;

    public List<T_COM_SYS_USER> queryForList(String c_USER_NAME, String c_STATUS, String c_COMPANY_ID) {
        return mapper.queryForList(
                StringUtils.isBlank(c_USER_NAME) ? null : c_USER_NAME,
                StringUtils.isBlank(c_STATUS) ? null : c_STATUS,
                StringUtils.isBlank(c_COMPANY_ID) ? null : c_COMPANY_ID
        );
    }

    public int getMaxId() {
        String id = mapper.getMaxId();
        int maxId = 0;
        if(StringUtils.isNotBlank(id)) {
            maxId = Integer.valueOf(id.replace(GenerateIDs.ID_TYPE_USER_ID,""));
        }
        return maxId;
    }
    public int getMaxPWDId() {
        String id = mapper.getMaxPWDId();
        int maxId = 0;
        if(StringUtils.isNotBlank(id)) {
            maxId = Integer.valueOf(id.replace(GenerateIDs.ID_TYPE_USER_PWD_ID,""));
        }
        return maxId;
    }

    public T_COM_SYS_USER get(String c_USER_ID, String c_LOGIN_NAME,String c_LOGIN_EMAIL) {
        return mapper.get(c_USER_ID,c_LOGIN_NAME,c_LOGIN_EMAIL);
    }

    public MapUtils insert(T_COM_SYS_USER user) {
        if (0 == GenerateIDs.getMaxUserId()) {
            GenerateIDs.setMaxUserId(getMaxId());
        }
        user.setC_USER_ID(GenerateIDs.GenerateId(GenerateIDs.ID_TYPE_USER_ID));
        if (null != get(user.getC_USER_ID(),null,null)) {
            GenerateIDs.setMaxUserId(getMaxId());
            user.setC_USER_ID(GenerateIDs.GenerateId(GenerateIDs.ID_TYPE_USER_ID));
        }
        if(null != get(null, user.getC_LOGIN_NAME(),null)) {
            return MapUtils.error("登录名重复！");
        }
        if (null != get(null, null, user.getC_USER_EMAIL())) {
            return MapUtils.error("邮箱重复！");
        }

         int result = mapper.insert(user);
        return 1 == result ? MapUtils.ok() : MapUtils.error("新增账户失败");
    }

    public MapUtils insertUserPwd(String c_USER_ID, String c_PASSWORD) {
        T_COM_SYS_USERPWD pwd = new T_COM_SYS_USERPWD();
        pwd.setC_PASSWORD(c_PASSWORD);
        pwd.setC_USER_ID(c_USER_ID);
        if (0 == GenerateIDs.getMaxUserPWDId()) {
            GenerateIDs.setMaxUserPWDId(getMaxPWDId());
        }
        pwd.setC_PASS_ID(GenerateIDs.GenerateId(GenerateIDs.ID_TYPE_USER_PWD_ID));
        if (null != mapper.getUserPwd(pwd.getC_PASS_ID())) {
            GenerateIDs.setMaxUserId(getMaxPWDId());
            pwd.setC_PASS_ID(GenerateIDs.GenerateId(GenerateIDs.ID_TYPE_USER_PWD_ID));
        }
        if (StringUtils.isBlank(pwd.getC_PASSWORD())) {
            pwd = generateUserPwd(pwd.getC_PASS_ID(),c_USER_ID,null,null,null);
        }
        pwd.setC_STATUS(SysConst.DICT_PWD_STATUS_NORMAL);
        pwd.setC_SALT(RandomStringUtils.randomAlphanumeric(20));
        pwd.setC_PWD_PLAINTEXT(pwd.getC_PASSWORD());
        pwd.setC_PASSWORD(ShiroUtils.sha256(pwd.getC_PASSWORD(), pwd.getC_SALT()));

        mapper.updatePwdStatus(c_USER_ID,SysConst.DICT_PWD_STATUS_UNABLE);
        return 1 == mapper.insertPwd(pwd) ? MapUtils.ok().put("originalPwd", pwd.getC_PWD_PLAINTEXT()) : MapUtils.error("新增密码失败");
    }

    public T_COM_SYS_USERPWD generateUserPwd(String c_PASS_ID,String c_USER_ID,String c_PASSWORD, String c_PWD_QUESTION , String c_PWD_ANSWER) {
        T_COM_SYS_USERPWD pwd = new T_COM_SYS_USERPWD();
        pwd.setC_PASS_ID(c_PASS_ID);
        pwd.setC_USER_ID(c_USER_ID);
        pwd.setC_SALT(RandomStringUtils.randomAlphanumeric(20));
        if (StringUtils.isBlank(c_PASSWORD)) {
            c_PASSWORD = KeysUtils.generatePlaintextKey(10);
            pwd.setC_PWD_PLAINTEXT(c_PASSWORD);
        }
        pwd.setC_PASSWORD(ShiroUtils.sha256(c_PASSWORD, pwd.getC_SALT()));
        pwd.setC_STATUS(SysConst.DICT_PWD_STATUS_NORMAL);
        pwd.setC_PWD_QUESTION(c_PWD_QUESTION);
        pwd.setC_PWD_ANSWER(c_PWD_ANSWER);
        return pwd;
    }

    public MapUtils update(T_COM_SYS_USER user) {
        if (StringUtils.isBlank(user.getC_USER_ID())) {
            return MapUtils.error("未能获取到账号信息，请刷新页面后重试！");
        }
        if (StringUtils.isBlank(user.getC_USER_EMAIL())) {
            return MapUtils.error("邮箱为空!");
        }
        if (StringUtils.isBlank(user.getC_COMPANY_ID())) {
            return MapUtils.error("关联公司为空");
        }
        if (StringUtils.isBlank(user.getC_ROLE_ID())) {
            return MapUtils.error("关联角色为空");
        }
        T_COM_SYS_USER temp = get(null, null, user.getC_USER_EMAIL());
        if (null != temp && !temp.getC_USER_ID().equals(user.getC_USER_ID())) {
            return MapUtils.error("邮箱重复！");
        }
        return 1 == mapper.update(user) ? MapUtils.ok() : MapUtils.error("修改登录用户失败");
    }

    @Transactional(rollbackFor={RuntimeException.class, Exception.class,SQLException.class})
    public MapUtils delete(String c_USER_ID) {
        try {
            if (1 == mapper.delete(c_USER_ID)) {
               mapper.deletePwd(c_USER_ID);
               return MapUtils.ok();
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return MapUtils.error("删除账户失败");
        }
        return MapUtils.error("删除账户失败");

    }

    public int updateUserStatus(String c_USER_ID , String c_STATUS) {
        return mapper.updateUserStatus(c_USER_ID,c_STATUS);
    }

    public UserInfo getUserInfoByLoginName(String loginName) {
        return mapper.getUserInfo(loginName);
    }

    public List<RoleInfo> queryUserRoles(String c_USER_ID) {
        return roleMapper.queryUserRoles(c_USER_ID);
    }


}
